package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.common.util.Utility;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.AreaService;
import co.gov.medellin.ssti.sub.model.service.ProgramaService;
import co.gov.medellin.ssti.sub.model.service.RepBeneficioOtorgadoService;
import co.gov.medellin.ssti.sub.model.service.ReporteTotalProgramasService;
import co.gov.medellin.ssti.sub.model.service.SubprogramaService;
import co.gov.medellin.ssti.sub.model.vo.AreaVO;
import co.gov.medellin.ssti.sub.model.vo.ProgramaVO;
import co.gov.medellin.ssti.sub.model.vo.ReporteTotalProgramasVO;
import co.gov.medellin.ssti.sub.model.vo.SubprogramaVO;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;

public class ReportTotalProgramasAction extends Action {
	@Autowired
	AreaService areaServiceImpl;
	@Autowired
	ProgramaService programaServiceImpl;
	@Autowired
	RepBeneficioOtorgadoService repBeneficioOtorgadoServiceImpl;
	@Autowired
	ReporteTotalProgramasService reporteTotalProgramasServiceImpl;
	@Autowired
	SubprogramaService subprogramaServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		Object codePrograma = (Object) request.getParameter("codePrograma");

		HttpSession session = request.getSession();
		UserVO user = (UserVO) session.getAttribute("userInfo");
		session.removeAttribute("msg");
		session.setAttribute("msg", "");
		Collection<ProgramaVO> programas = null;
		Collection<SubprogramaVO> subprogramas = null;
		Collection<AreaVO> areas = null;

		session.removeAttribute("Beneficios");
		String strarea = request.getParameter("codearea");

		try {

			areas = areaServiceImpl.findAreasAuthorized(
					String.valueOf(user.getCode()), user.getUserGroupName());
		} catch (DAOException e) {
			SUBException.logDebugError("", e);
		}
		if (areas.size() > 0) {
			session.setAttribute("areas", areas);
			if ((Object) strarea != null && !strarea.equals("nulo")) {
				session.removeAttribute("programas");
				session.removeAttribute("subprogramas");
				try {

					ProgramaVO objProgramaVO = new ProgramaVO();
					objProgramaVO.setCodeArea(new Long(strarea));
					programas = programaServiceImpl.findProgramaByCriteria(
							objProgramaVO, user.getUserGroupName(),
							user.getCode(), user.getCodeArea());
				} catch (DAOException e) {
					SUBException.logDebugError("", e);
				}
				if (programas.size() > 0) {
					session.setAttribute("programas", programas);
				}
			} else {
				try {
					programas = repBeneficioOtorgadoServiceImpl
							.findProgramaByUserReport(user.getCode(),
									user.getUserGroupName(), user.getCodeArea());
				} catch (DAOException e) {
					SUBException.logDebugError("", e);
				}
				session.removeAttribute("msg");
				if (programas.size() > 0) {
					session.setAttribute("programas", programas);
				} else {
					session.setAttribute("msg",
							"No se encontraron programas vigentes a la fecha..");
				}
			}
			if (codePrograma != null) {
				String codpro = (String) codePrograma;
				if (!codpro.equals("nulo")) {
					try {
						String strCodeProg = (String) codePrograma;
						SubprogramaVO vo = new SubprogramaVO();
						vo.setCode(Long.valueOf(strCodeProg));
						subprogramas = subprogramaServiceImpl
								.findAllowedSubprograma(vo, user.getCode(),
										user.getUserGroupName(),
										user.getCodeArea());
						// subprogramas = repBeneficioOtorgadoServiceImpl
						// .findSubProgramaByUserReport(user.getCode(),
						// user.getUserGroupName(), strCodeProg,
						// user.getCodeArea());
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}
					session.removeAttribute("msg");
					if (subprogramas.size() > 0) {
						session.setAttribute("subprogramas", subprogramas);
					} else {
						session.setAttribute("msg",
								"No se encontraron subprogramas asociados a este programa que esten vigentes..");
					}
				} else {
					session.setAttribute("msg", "");
					session.removeAttribute("subprogramas");
				}
			}
		} else {
			session.setAttribute("msg",
					"No se encontraron sedes vigentes a la fecha..");
		}

		String accion = (request.getParameter("acciones") == null) ? ""
				: request.getParameter("acciones");
		Object codeArea = request.getParameter("code");
		if (codeArea == null)
			codeArea = request.getParameter("codearea");

		Object codeSubprograma = request.getParameter("codeSubPrograma");

		String codeArea1 = (String) codeArea;
		String codeSubprograma1 = (String) codeSubprograma;
		String codePrograma1 = (String) codePrograma;

		boolean continuar = true;

		// fecha inicial
		String fechaini = (request.getParameter("fechaInicial") == null) ? ""
				: request.getParameter("fechaInicial");
		String fechafinal = (request.getParameter("fechaFinal") == null) ? ""
				: request.getParameter("fechaFinal");

		// validar fechas..
		if (!fechaini.equals("") && !fechafinal.equals("")) {
			if (!Utility.isDateValid(fechaini)) {
				request.setAttribute("errorfecha",
						"La fecha inicial es incorrecta");
				continuar = false;
			} else if (!Utility.isDateValid(fechafinal)) {
				request.setAttribute("errorfecha",
						"La fecha final es incorrecta");
				continuar = false;
			} else {
				Date fIni;
				Date fFin;
				try {
					fIni = new SimpleDateFormat(Utility.DATE_FORMAT)
							.parse(fechaini);
					fFin = new SimpleDateFormat(Utility.DATE_FORMAT)
							.parse(fechafinal);
					if (fIni.after(fFin)) {
						request.setAttribute("errorfecha",
								"La fecha inicial es mayor a la final");
						continuar = false;
					}
				} catch (ParseException e) {
					continuar = false;
				}
			}
		}

		if (continuar) {
			session.removeAttribute("beneficiosSede");
			if (accion != null) {
				if (accion.equals("BuscarTodo")) {

					Collection<ReporteTotalProgramasVO> cobeneficio = null;
					try {

						ReporteTotalProgramasVO objtotalprog = new ReporteTotalProgramasVO();
						if (codeArea != null && !codeArea1.equals("nulo")) {
							objtotalprog
									.setCodeArea(new Long((String) codeArea));
						}
						if (codePrograma != null
								&& !codePrograma1.equals("nulo")) {
							objtotalprog.setCodePrograma(new Long(
									(String) codePrograma));
						}
						if (codeSubprograma != null
								&& !codeSubprograma1.equals("nulo")) {
							objtotalprog.setCodeSubprograma(new Long(
									(String) codeSubprograma));
						}
						if (fechaini != null && !fechaini.equals("nulo")) {
							objtotalprog.setDesde(fechaini);
						} else {
							objtotalprog.setDesde("");
						}
						if (fechafinal != null && !fechafinal.equals("nulo")) {
							objtotalprog.setHasta(fechafinal);
						} else {
							objtotalprog.setHasta("");
						}

						session.setAttribute("Parametros", objtotalprog);

						objtotalprog = reporteTotalProgramasServiceImpl
								.findFilters(objtotalprog);
						cobeneficio = reporteTotalProgramasServiceImpl
								.findReporteTotalProgramas(objtotalprog);
						if (cobeneficio != null) {
							if (cobeneficio.size() > 0) {
								session.setAttribute("Beneficios", cobeneficio);
								session.setAttribute("Filters", objtotalprog);
							} else {
								session.removeAttribute("Beneficios");
							}
						}
						objtotalprog = null;
					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}

				}
			} else {
				session.removeAttribute("Beneficios");
			}
		}

		Object obIR = request.getParameter("seleccionar");
		if (obIR == null || accion.equals("BuscarSubprogrmas")
				|| accion.equals("areas")) {
			return mapping.findForward("success");
		} else {
			return mapping.findForward("ir");
		}

	}
}